﻿using Huirui.Cavan.Application.MainBoundedContext.SystemModule;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using Huirui.Cavan.Presentation.Seedwork;
using Huirui.Cavan.Presentation.ViewModel.SystemModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Domain.Seedwork;
using Newtonsoft.Json;

namespace Huirui.Cavan.Presentation.Controller.SystemModule
{
    public class SysActionController : EntityController<SysAction, int, SysActionSearch, ISysActionViewModel, ISysActionAppService>, ISysActionController
    {
        private IEmployeeAppService EmployeeAppService { get; set; }
        private IUserAccountAppService UserAccountAppService { get; set; }
        private IRoleAppService RoleAppService { get; set; }

        public override string ControllerName
        {
            get { return ControllerConst.SYSACTION; }
        }

        public override bool UseDenied
        {
            get { return false; }
        }

        public SysActionController()
        {
            this.Model = ModelFactory.CreateModel<ISysActionViewModel>();
        }

        [ActionName(ActionConst.AUTHORIZE)]
        [HttpGet]
        [ActionPermissionAttribute(Name = "authorize_query")]
        public ActionResult AddActionAuthority()
        {
            IList<Employee> employees = this.EmployeeAppService.GetBySearch(new EmployeeSearch() { CorporationCode = SecurityAppService.Corporation.Id, HasUserAccount = true }).ToList();
            this.Model.AuthorizeEmployees.Add(new SelectListItem() { Selected = true, Text = "请选择", Value = "0" });
            foreach (Employee employee in employees)
            {
                SelectListItem item = new SelectListItem() { Text = employee.Name, Value = employee.UserAccount.Id.ToString() };
                this.Model.AuthorizeEmployees.Add(item);
            }
            return View("~/Views/System/v1/addActionPermission.cshtml", this.Model);
        }

        [ActionName(ActionConst.AUTHORIZE)]
        [HttpPost]
        [ActionPermissionAttribute(Name = "authorize_edit")]
        public JsonResult AddActionAuthority(SysActionViewModel model)
        {
            BoolGenericResult<UserAccount> result = null;
            List<RoleActionJson> roleActionJsons = new List<RoleActionJson>();
            if (model.PermissionActions.IsNotEmpty())
            {
                roleActionJsons = JsonConvert.DeserializeObject<List<RoleActionJson>>(model.PermissionActions);
            }

            List<SysAction> actions = new List<SysAction>();
            foreach (RoleActionJson json in roleActionJsons)
            {
                SysAction sa = new SysAction() { Id = json.ActionID };
                actions.Add(sa);
            }
            result = this.AppService.AddActionToUserAccount(model.UserAccountID, model.OnlyQuerySelfData, model.CannotQueryPurchaseCostAndAmount, model.CannotQuerySalesCostAndAmount, actions);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult, "application/json");
        }

        [ActionName(ActionConst.LIST)]
        [ActionPermissionAttribute(Name = "authorize_query")]
        public JsonResult SelectActionPermission(int id)
        {
            IList<SysAction> allActions = this.AppService.GetBySearch(new SysActionSearch() { CurrentPage = 0 }).ToList();

            IList<SysAction> permissionActions = null;
            Role role = null;
            RoleActionJsonViewModel json = new RoleActionJsonViewModel();
            if (id > 0)
            {
                UserAccount authorizeUserAccount = this.UserAccountAppService.GetById(id);
                json.OnlyQuerySelfData = authorizeUserAccount.UserAccountProperty.OnlyQuerySelfData;
                json.CannotQueryPurchaseCostAndAmount = authorizeUserAccount.UserAccountProperty.CannotQueryPurchaseCostAndAmount;
                json.CannotQuerySalesCostAndAmount = authorizeUserAccount.UserAccountProperty.CannotQuerySalesCostAndAmount;
                role = this.RoleAppService.GetById(authorizeUserAccount.Role.Id);
                permissionActions = role.Actions;
            }

            
            json.rows = new List<RoleActionJson>();
            foreach (SysAction sa in allActions)
            {
                RoleActionJson raj = new RoleActionJson()
                {
                    HasPermission = false,
                    ModuleName = sa.Controller.Module.Name,
                    RoleId = role.IsNotNull() ? role.Id : 0,
                    UserAccountId = id,
                    ActionPart1 = "",
                    ActionPart2 = sa.ChineseName.Split(',')[1],
                    ActionID = sa.Id,
                    IncludeAction = sa.IncludeAction,
                    ControllerID = sa.Controller.Id
                };
                if (!allActions.Any(a => sa.Id > a.Id && a.Controller.Id == sa.Controller.Id))
                {
                    raj.ActionPart1 = sa.ChineseName.Split(',')[0];
                }
                if (permissionActions.IsNotNull() && permissionActions.Any(pa => pa.Id == sa.Id))
                {
                    raj.HasPermission = true;
                }
                json.rows.Add(raj);
            }
            json.total = allActions.Count;
            return Json(json, "application/json");
        }
    }
}
